<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1080">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
      :disabled="disabled"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="客户编号" prop="customerId">
            <el-select v-model="formData.customerId" placeholder="请选择客户">
              <el-option
                v-for="cus in customerList"
                :key="cus.id"
                :label="cus.name"
                :value="cus.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="下单时间" prop="orderTime">
            <el-date-picker v-model="formData.orderTime" type="date" placeholder="请选择" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="销售员" prop="saleUserId">
            <el-select
              v-model="formData.saleUserList"
              clearable
              filterable
              placeholder="请选择"
              class="!w-1/1"
            >
              <el-option
                v-for="item in userList"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结算账户" prop="accountId">
            <el-select
              v-model="formData.accountList"
              clearable
              filterable
              placeholder="请选择"
              class="!w-1/1"
            >
              <el-option
                v-for="item in accountList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="优惠率" prop="discountPercent">
            <el-input-number
              v-model="formData.discountPercent"
              :min="0"
              controls-position="right"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="定金金额" prop="depositPrice">
            <el-input-number v-model="formData.depositPrice" :min="0" controls-position="right" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="附件" prop="fileUrl">
            <UploadFile :is-show-tip="false" v-model="formData.fileUrl" :limit="5" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" type="textarea" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <div v-if="formType.value === 'detail'">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="销售单号" prop="no">
                <el-input v-model="formData.no" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="销售状态" prop="status">
                <el-input v-model="formData.status" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合计总数" prop="totalCount">
                <el-input v-model="formData.totalCount" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="最终合计价格" prop="totalPrice">
                <el-input v-model="formData.totalPrice" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合计物品价格" prop="totalProductPrice">
                <el-input v-model="formData.totalProductPrice" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="优惠金额" prop="discountPrice">
                <el-input v-model="formData.discountPrice" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="优惠金额" prop="discountPrice">
                <el-input v-model="formData.discountPrice" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="累计预收" prop="accumulatedAdvance">
                <el-input v-model="formData.accumulatedAdvance" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="销售出库数量" prop="outCount">
                <el-input v-model="formData.outCount" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="销售退货数量" prop="returnCount">
                <el-input v-model="formData.returnCount" />
              </el-form-item>
            </el-col> </el-row
        ></div>
      </el-row>
      <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px" v-if="formType.value != 'detail'">
        <div >
          <el-tab-pane label="物品信息" name="item">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="物品" prop="productId">
                  <el-select v-model="formData.productId" placeholder="请选择">
                    <el-option
                      v-for="pro in productList"
                      :key="pro.id"
                      :label="pro.name"
                      :value="pro.id"
                      class="!w-1/1"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="物品单位" prop="productUnitId">
                  <el-select v-model="formData.productUnitId" placeholder="请选择部门">
                    <el-option
                      v-for="pro in productUnitList"
                      :key="pro.id"
                      :label="pro.name"
                      :value="pro.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="物品单价" prop="productPrice">
                  <el-input-number
                    v-model="formData.productPrice"
                    :min="0"
                    controls-position="right"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="物品数量" prop="count">
                  <el-input-number v-model="formData.count" :min="0" controls-position="right" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="税率(百分比)" prop="taxPercent">
                  <el-input v-model="formData.taxPercent" placeholder="请输入" class="!w-1/1">
                    <template #append>%</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="formData.remark" type="textarea" placeholder="请输入" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </div>
      </el-tabs>
      <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px" v-if="formType.value == 'detail'">
        <el-tab-pane label="物品信息" name="item">
          <div v-for="(item, index) in formData.items" :key="index" class="border-b">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item
                  :label="index === 0 ? '物品' : ''"
                  :prop="`items.${index}.productId`"
                  :rules="formRules.itemsProductId"
                >
                  <el-select v-model="item.productId" placeholder="请选择" class="!w-1/1">
                    <el-option
                      v-for="pro in productList"
                      :key="pro.id"
                      :label="pro.name"
                      :value="pro.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  :label="index === 0 ? '物品单位' : ''"
                  :prop="`items.${index}.productUnitId`"
                  :rules="formRules.itemsProductUnitId"
                >
                  <el-select v-model="item.productUnitId" placeholder="请选择单位" class="!w-1/1">
                    <el-option
                      v-for="unit in productUnitList"
                      :key="unit.id"
                      :label="unit.name"
                      :value="unit.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  :label="index === 0 ? '物品单价' : ''"
                  :prop="`items.${index}.productPrice`"
                  :rules="formRules.itemsProductPrice"
                >
                  <el-input-number
                    v-model="item.productPrice"
                    :min="0"
                    controls-position="right"
                    class="!w-1/1"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  :label="index === 0 ? '物品数量' : ''"
                  :prop="`items.${index}.count`"
                  :rules="formRules.itemsCount"
                >
                  <el-input-number
                    v-model="item.count"
                    :min="0"
                    controls-position="right"
                    class="!w-1/1"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  :label="index === 0 ? '税率' : ''"
                  :prop="`items.${index}.taxPercent`"
                >
                  <el-input v-model="item.taxPercent" placeholder="请输入税率" class="!w-1/1">
                    <template #append>%</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="index === 0 ? '备注' : ''" :prop="`items.${index}.remark`">
                  <el-input v-model="item.remark" placeholder="物品备注" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading" v-if="!disabled">
        确 定
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { SaleOrderApi, SaleOrderVO } from '@/api/erp/sale/order'
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { productUnitApi } from '@/api/erp/foundation/productUnit'
import { CustomerApi, CustomerVO } from '@/api/erp/sale/customer'
import { AccountApi, AccountVO } from '@/api/erp/finance/account'
import { erpPriceInputFormatter, erpPriceMultiply } from '@/utils'
import * as UserApi from '@/api/system/user'
// import StockList from '../../logistics/warehouse/components/StockList.vue'
/** ERP 销售订单表单 */
defineOptions({ name: 'SaleOrderForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改；detail - 详情
const formData = ref({
  id: undefined,
  customerId: undefined,
  orderTime: undefined,
  saleUserId: undefined,
  remark: undefined,
  fileUrl: '',
  discountPercent: undefined,
  depositPrice: undefined,
  totalPrice: undefined,
  items: [
    {
      productId: undefined,
      productUnitId: undefined,
      productPrice: undefined,
      count: undefined,
      taxPercent: undefined,
      remark: undefined
    }
  ],
  no: undefined // 订单单号，后端返回
})
const salesType = ref('1')
const formRules = reactive({
  customerId: [{ required: true, message: '客户不能为空', trigger: 'blur' }],
  orderTime: [{ required: true, message: '下单时间不能为空', trigger: 'blur' }],
  saleUserId: [{ required: true, message: '销售员不能为空', trigger: 'blur' }],
  accountId: [{ required: true, message: '结算账户不能为空', trigger: 'blur' }],
  productId: [{ required: true, message: '物品不能为空', trigger: 'blur' }],
  productUnitId: [{ required: true, message: '物品单位不能为空', trigger: 'blur' }],
  count: [{ required: true, message: '物品数量不能为空', trigger: 'blur' }],
  discountPercent: [{ required: true, message: '优惠率不能为空', trigger: 'blur' }]
})
const disabled = computed(() => formType.value === 'detail')
const formRef = ref() // 表单 Ref
const customerList = ref<CustomerVO[]>([]) // 客户列表
const accountList = ref<AccountVO[]>([]) // 账户列表
const userList = ref<UserApi.UserVO[]>([]) // 用户列表
const productList = ref<ProductVO[]>([]) // 物品列表
const productUnitList = ref<any[]>([]) // 单位列表

/** 子表的表单 */
const subTabsName = ref('item')
const itemFormRef = ref()

// /** 计算 discountPrice、totalPrice 价格 */
// watch(
//   () => formData.value,
//   (val) => {
//     if (!val) {
//       return
//     }
//     const totalPrice = val.items.reduce((prev, curr) => prev + curr.totalPrice, 0)
//     const discountPrice =
//       val.discountPercent != null ? erpPriceMultiply(totalPrice, val.discountPercent / 100.0) : 0
//     formData.value.discountPrice = discountPrice
//     formData.value.totalPrice = totalPrice - discountPrice
//   },
//   { deep: true }
// )

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type) + '销售订单'
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await SaleOrderApi.getSaleOrder(id)
    } finally {
      formLoading.value = false
    }
  }
  const queryParams = reactive({
    pageNo: 1,
    pageSize: 100
  })
  // 加载客户列表
  customerList.value = (await CustomerApi.getCustomerPage(queryParams)).list
  // 加载用户列表
  userList.value = (await UserApi.getUserPage(queryParams)).list
  // 加载物品列表
  productList.value = (await ProductApi.getProductPage(queryParams)).list
  productUnitList.value = (await productUnitApi.pageList(queryParams)).list
  // 加载账户列表
  // accountList.value = await AccountApi.getAccountSimpleList()
  const defaultAccount = accountList.value.find((item) => item.defaultStatus)
  if (defaultAccount) {
    formData.value.accountId = defaultAccount.id
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  await itemFormRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as SaleOrderVO
    if (formType.value === 'create') {
      // await SaleOrderApi.createSaleOrder(data)
      message.success(t('common.createSuccess'))
    } else {
      // await SaleOrderApi.updateSaleOrder(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    customerId: undefined,
    orderTime: undefined,
    saleUserId: undefined,
    remark: undefined,
    fileUrl: '',
    discountPercent: 0,
    depositPrice: 0,
    totalPrice: 0,
    item: [
      {
        productId: undefined,
        productUnitId: undefined,
        productPrice: undefined,
        count: undefined,
        taxPercent: undefined,
        remark: undefined
      }
    ],
    no: undefined // 订单单号，后端返回
  }
  formRef.value?.resetFields()
}
</script>
